//index.js
//获取应用实例
const app = getApp()
const networkManager = require('../../utils/networkManager.js')
const queryString = require('../../utils/query-string.js')


Page({
  data: {
    phone: '',
    captchas: '',
    countDownTime: 30,
    showCountDown: false,
  },
  //事件处理函数
  gotoAgreement() {
    wx.navigateTo({
      url: '/pages/agreement/index',
    })
  },
  inputPhoneNum(e) {
    this.setData({phone: e.detail.value})
  },
  inputCaptchas(e) {
    this.setData({ captchas: e.detail.value })
  },
  login() {
    const {phone, captchas} = this.data
    networkManager._post_json('/login/newLogin', { phone, captchas, country: {} }, (res) => {

      if (res.code !== 0) {
        return wx.showToast({
          icon: 'none',
          title: res.errorMessage,
        })
      }

      wx.setStorageSync('userInfo', res.data)

      wx.navigateBack({
        
      })
     
    }, (err) => {
      wx.showToast({
        title: err.message
      })
    })
  },
  getCode() {
    const {phone, captchas} = this.data

    if (!phone) return wx.showToast({
      icon: 'none',
      title: '请输入手机号',
    })

    networkManager._get('/login/captchas?phone=' + phone + '&prefix=86', (res) => {
      if (res.code === 0) {
        this.setData({showCountDown: true})
        this.runCountDown()
      }

      
      wx.showToast({
        title: '验证码已发送！'
      })
    }, (err) => {
      wx.showToast({
        icon: 'error',
        title: err.message
      })
    })
    
  },

  runCountDown: function() {
    const countdown = () => {
      setTimeout(() => {
        const countDownTime = this.data.countDownTime

        if (countDownTime > 1) {
          this.setData({ countDownTime: countDownTime - 1})
          countdown()
        } else {
          this.setData({ countDownTime: 30, showCountDown: false })
        }
        
      }, 1000)
    }

    countdown()
  },
  onLoad: function () {
    wx.setNavigationBarTitle({
      title: 'Ticket太票',
    })
  },
})
